<template>
  <div class="tinymce-editor">
    <Editor
      v-model="content"
      :init="init"
      :disabled="disabled"
      @onClick="onClick"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import axios from "axios";
import { resourceinfosave } from "@/api/naturalRes";

// 核心
import "tinymce/themes/silver/theme";
import "tinymce/models/dom/model";

// 插件
import "tinymce/icons/default";
import "tinymce/plugins/advlist";
import "tinymce/plugins/anchor";
import "tinymce/plugins/autolink";
import "tinymce/plugins/autoresize";
import "tinymce/plugins/image";
import "tinymce/plugins/link";
import "tinymce/plugins/lists";
import "tinymce/plugins/media";
import "tinymce/plugins/code";
import "tinymce/plugins/lists";
import "tinymce/plugins/table";
import "tinymce/plugins/wordcount";

// Props 定义
interface Props {
  modelValue?: string;
  disabled?: boolean;
  id?: string;
  plugins?: string | string[];
  toolbar?: string | string[];
  data?: any;
}
const route = useRoute();
const props = withDefaults(defineProps<Props>(), {
  modelValue: "",
  disabled: false,
  id: "111",
  plugins: "advlist autolink lists link image table wordcount",
  toolbar:
    "undo redo | formatselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media table | removeformat",
  data: {},
});

// Emits 定义
const emit = defineEmits<{
  (e: "update:modelValue", value: string): void;
  (e: "update:id", value: string): void;
  (e: "onClick", event: any): void;
}>();

// 编辑器内容
const content = ref(props.modelValue);
const editorId = ref(props.id);
// 编辑器配置
const init = {
  language_url: "/tinymce/langs/zh_CN.js",
  language: "zh_CN",
  skin_url: "/tinymce/skins/ui/oxide",
  content_css: "/tinymce/skins/content/default/content.css",
  plugins: props.plugins,
  toolbar: props.toolbar,
  branding: false,
  menubar: false,
  // 修改图片上传处理器
  images_upload_handler: async (blobInfo: any) => {
    try {
      const formData = new FormData(); // 修正变量名
      formData.append("file", blobInfo.blob());
      formData.append("resId", editorId.value);
      console.log("formData", formData, props.id);

      const response: any = await axios({
        url: "http://10.222.125.103:18086/resource/info/save/img",
        method: "post",
        headers: {
          "Content-Type": "multipart/form-data",
        },
        data: formData,
        timeout: 1000 * 20,
      });
      console.log("上传成功，返回数据：", response.data);

      if (response.data.code === 200) {
        // return `${import.meta.env.VITE_API_URL}/${response.data.image_url}`;
        console.log("response.data", response.data.data);

        return response.data.data;
      } else {
        throw new Error(response.message || "上传失败");
      }
    } catch (error) {
      console.error("上传错误:", error);
      throw new Error("图片上传失败，请重试");
    }
  },
  setup: function (editor) {
    // 聚焦事件
    let fristcreate = true;
    editor.on("focus", async function (e) {
      console.log("编辑器获得焦点", route.params.id);
      if (route.params.id == "add" && fristcreate) {
        console.log(
          "新增",
          fristcreate,
          props.data.resName,
          props.data.dynamic,
          props.data.resType
        );
        if (Object.keys(props.data).length === 0) {
          ElMessage.error("请先填写资源类型信息");
        } else if (!props.data.resName) {
          ElMessage.error("请先填写资源名称");
        } else if (!props.data.dynamic && props.data.dynamic != 0) {
          ElMessage.error("请先选择资源类别");
        } else if (!props.data.resType) {
          ElMessage.error("请先选择资源类型名称");
        } else {
          const data: any = await resourceinfosave(props.data);
          fristcreate = false;
          editorId.value = data;
          emit("update:id", data);
          emit("onClick", data);
        }
      }
      // 可以在这里添加自定义逻辑，比如显示工具栏等
    });

    // 失焦事件
    editor.on("blur", function (e) {
      console.log("编辑器失去焦点");
      // 可以在这里添加自定义逻辑，比如隐藏工具栏等
    });
  },
  // 文件选择配置
  file_picker_types: "image",
  images_file_types: "jpg,jpeg,png,gif",
  image_advtab: true,
  // 允许拖拽上传
  draggable_modal: true,
  // 图片上传配置
  images_upload_base_path: import.meta.env.VITE_API_URL,
  // 图片上传URL验证
  images_upload_credentials: true,
  // 开启调试模式，方便排查问题
  debug: true,
};

// 监听 props 变化
watch(
  () => props.modelValue,
  (newValue) => {
    if (content.value !== newValue) {
      console.log("props.modelValue changed:", props.id);

      content.value = newValue;
    }
  }
);

// 监听内容变化
watch(
  () => content.value,
  (newValue) => {
    emit("update:modelValue", newValue);
  }
);

// 点击事件处理
const onClick = (e: any) => {};

// 清空内容方法
const clear = () => {
  content.value = "";
};

// 初始化编辑器
onMounted(() => {
  tinymce.init({});
});

// 暴露方法给父组件
defineExpose({
  clear,
});
</script>

<style lang="scss" scoped>
.tinymce-editor {
  width: 100%;
}

:deep(.tox-tinymce) {
  border-radius: 4px;
}
</style>

<style lang="scss">
.tox-tinymce-aux {
  z-index: 99999 !important;
}
.tinymce.ui.FloatPanel {
  z-index: 99;
}
</style>
